package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.AttendanceSheet;
import cn.wolfcode.crm.query.ShareQueryObject;
import cn.wolfcode.crm.service.IAttendanceSheetService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("attendancesheet")
public class AttendanceSheetController {

    @Autowired
    private IAttendanceSheetService attendanceSheetService;


    //考勤管理首页
    @RequestMapping("")
    public String index(){

        return "attendancesheet/list";
    }

    //考勤管理列表
    @RequestMapping("list")
    @ResponseBody
    public Object list(ShareQueryObject qo){

        PageResult result = attendanceSheetService.query(qo);

        return result;
    }

    @RequestMapping("listdData")
    public Object listData(ShareQueryObject qo){


        return attendanceSheetService.selectAll();
    }


    @RequestMapping({"/exportExcel"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response, String[] titles) throws Exception {

            for(int i = 0; i < titles.length; ++i) {
                 titles[i] = URLDecoder.decode(titles[i], "UTF-8");
        }

        response.setHeader("Content-Disposition", "attachment;filename=bigClient.xls");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("考勤管理");
        HSSFRow row = sheet.createRow(0);

        for(int i = 0; i < titles.length; ++i) {
            row.createCell(i).setCellValue(titles[i]);
        }
        List<AttendanceSheet> list = this.attendanceSheetService.selectAll();


        for(int i = 0; i < list.size(); ++i) {
            AttendanceSheet data = (AttendanceSheet) list.get(i);
            row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(data.getId().longValue());
            row.createCell(1).setCellValue(data.getName());
            row.createCell(2).setCellValue(format.format(new Date(data.getSignintime().toString())));
            row.createCell(3).setCellValue(format.format(new Date(data.getSignbacktime().toString())));
            row.createCell(4).setCellValue(data.isSignoutstate());
            row.createCell(5).setCellValue(data.isSigninstate());;
        }

        workbook.write(response.getOutputStream());
    }
    }
